﻿using OnCommon;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Sockets;
using System.Text;
using System.Threading;

namespace OnLineLogFileClient
{
    public abstract class SocketTcpJobAsync : IDisposable
    {
        protected SocketTcpClient client;

        /// <summary>
        /// 消息通知事件
        /// </summary>
        public event Action<string> NotifyMsgEvent;

        protected bool HasConnected { get; set; }

        protected bool TryConnect()
        {
            this.HasConnected = false;
            if (client != null)
            {
                try { client.Dispose(); }
                catch { }
            }

            int retryFrequency = 0;
            do
            {
                try
                {
                    this.InvMsg("正在第" + retryFrequency + "次连接到服务器......");
                    client = new SocketTcpClient();
                    client.Connect("192.168.2.6", 20141);//服务器地址配置出去
                    this.HasConnected = true;
                    this.InvMsg("socket connected");
                    return true;
                }
                catch (SocketException sex)
                {
                    this.InvMsg("连接到服务器失败，5分钟后第" + retryFrequency + "次重试。" + sex.Message);
                    Thread.Sleep(60000 * 5);//休眠一分钟
                }
                catch (Exception ex)
                {
                    LogServices.LogService.Instance.Write(ex);
                    return false;
                }
                retryFrequency++;
            } while (retryFrequency < 4);

            this.InvMsg("服务器连接不上，请检查");
            return false;
        }

        public abstract void Run();

        protected void InvMsg(string msg)
        {
            if (this.NotifyMsgEvent != null)
            {
                this.NotifyMsgEvent(msg);
            }
        }


        public virtual void Dispose()
        {
            if (this.client != null)
            {
                this.client.Dispose();
                this.client = null;
            }
        }
    }
}
